package com.security.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.security.constant.RedisConstant;
import com.security.domain.bo.R;
import com.security.domain.po.Account;
import com.security.exception.PhoneNotFoundException;
import com.security.mapper.AccountMapper;
import com.security.mapper.RoleMapper;
import com.security.service.AccountService;
import com.security.utils.EmailUtil;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 用户服务实现类
 *
 * @author DblSun
 */
@Slf4j
@Service
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String From;
    @Value("${spring.mail.to}")
    private String To;

    // 根据手机号查询用户信息
    public UserDetails loadUserByPhone(String phone) throws UsernameNotFoundException {
        Account account = accountMapper.getAccountByPhone(phone);
        if (account == null) {
            throw new PhoneNotFoundException("用户未注册");
        }
        account.setRoles(roleMapper.getRoleById(account.getId()));
        return account;
    }

    // 根据用户名查询用户信息
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountMapper.getAccountByUsername(username);
        if (account == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        account.setRoles(roleMapper.getRoleById(account.getId()));
        return account;
    }

    // 发送验证码
    public R<String> sendCaptcha(String phone) throws MessagingException {
        String captcha = RandomUtil.randomNumbers(6);
        EmailUtil.sendSimpleMail(javaMailSender, captcha, From, To);
        stringRedisTemplate
                .opsForHash().put(RedisConstant.ApplicationName + RedisConstant.USER_CAPTCHA, phone, captcha);
        stringRedisTemplate.expire(RedisConstant.ApplicationName + RedisConstant.USER_CAPTCHA + phone,
                RedisConstant.USER_CAPTCHA_EXPIRE, TimeUnit.MINUTES);
        log.info("邮箱 {} 收到的验证码为：{}", To, captcha);
        return R.success("验证码发送成功");
    }
}
